/**
 * Copyright (c) 2019 AsHacker All rights reserved.
 * <p>
 * http://www.ashacker.com
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.three;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.util.BytePictureUtils;
import io.renren.common.utils.DateUtils;
import io.renren.modules.app.constants.StringConstants;
import io.renren.modules.oss.cloud.AliyunCloudStorageService;
import io.renren.modules.oss.cloud.CloudStorageConfig;
import io.renren.modules.sys.controller.AbstractController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 该类描述：
 * base64位图片存储到硬盘中，并且返回url
 */
@RestController
@RequestMapping("/app")
@Api("第三方操作")
public class WxController extends AbstractController {

    String rgex = "data:image/(.*?);base64";

    @ResponseBody
    @PostMapping("saveImg")
    @ApiOperation("保存图片")
    public String saveImg(@RequestBody JSONObject data) throws Exception {

        logger.info("saveImg方法执行开始：传入参数为   " + data);

        Map<String, Object> datas = new HashMap<String, Object>();
        String baseImg = data.getString("baseImg");
        String baseImg1 = data.getString("baseImg1");
        String cm000034name = data.getString("cm000034name");
        String docType = data.getString("type");
        //定义一个正则表达式的筛选规则，为了获取图片的类型
        String type = getSubUtilSimple(baseImg, rgex);
        //去除base64图片的前缀
        if (baseImg1 != null)
            baseImg1 = baseImg1.replaceFirst("data:(.+?);base64,", "");
        baseImg = baseImg.replaceFirst("data:(.+?);base64,", "");
        byte[] b, b1;
        byte[] bs, bs1 = new byte[1];
        OutputStream os = null, os1 = null;
        //把图片转换成二进制
        b = Base64.decode(baseImg.replaceAll(" ", "+"));
        //生成路径
        BASE64Decoder d = new BASE64Decoder();
        // 保存
        try {
            bs = d.decodeBuffer(Base64.encode(b));
            if (baseImg1 != null) {
                b1 = Base64.decode(baseImg1.replaceAll(" ", "+"));
                bs1 = d.decodeBuffer(Base64.encode(b1));
            }
            if (Constants.storeLocal) {
//				os = new FileOutputStream(imageFile);
                os.write(bs);
//                os1.write(bs1);
            } else {
                //上传Byte数组
                CloudStorageConfig config = new CloudStorageConfig();
                config.setAliyunAccessKeyId(Constants.accessKeyId);
                config.setAliyunAccessKeySecret(Constants.accessKeySecret);
                config.setAliyunEndPoint(Constants.endpoint);
                config.setAliyunBucketName(Constants.bucketName);
                config.setAliyunDomain("https://pulilai.oss-cn-beijing.aliyuncs.com");
                config.setAliyunPrefix("qianming");
                String url = new AliyunCloudStorageService(config).uploadSuffix(bs, "_" + cm000034name + "." + type);
                String url1 = "";
                if (baseImg1 != null) {
                    url1 = new AliyunCloudStorageService(config).uploadSuffix(bs1, "_" + cm000034name + "." + type);
                }
                datas = data.getInnerMap();
                //网络图片
                datas.put("cf_2108", new PictureRenderData(200, 100, ".png", BytePictureUtils.getUrlByteArray(url)));
                if (!"".equals(url))
                    datas.put("cf_2109", new PictureRenderData(200, 100, ".png", BytePictureUtils.getUrlByteArray(url1)));
                if (docType.equals("installConfirm"))
                    ReadAndWriteDoc.readwriteWord(StringConstants.linuxDocPath + "installConfirm.docx", datas);
                else if (docType.equals("installDebugForm"))
                    ReadAndWriteDoc.readwriteWord(StringConstants.linuxDocPath + "installDebugForm.docx", datas);
                else if (docType.equals("productSubmitForm"))
                    ReadAndWriteDoc.readwriteWord(StringConstants.linuxDocPath + "productSubmitForm.docx", datas);
                else if (docType.equals("techParameterForm"))
                    ReadAndWriteDoc.readwriteWord(StringConstants.linuxDocPath + "techParameterForm.docx", datas);
                else if (docType.equals("sellServiceForm"))
                    ReadAndWriteDoc.readwriteWord(StringConstants.linuxDocPath + "sellServiceForm.docx", datas);
                else if (docType.equals("debugPersonServiceForm"))
                    ReadAndWriteDoc.readwriteWord(StringConstants.linuxDocPath + "debugPersonServiceForm.docx", datas);
                else if (docType.equals("serviceSubmitOrder"))
                    ReadAndWriteDoc.readwriteWord(StringConstants.linuxDocPath + "serviceSubmitOrder.docx", datas);

                logger.info("saveImg方法执行结束：返回值为   " + "{\"url\":\"" + url + "\", \"url1\":\"" + url1 + "\", \"state\":\"ok\"}");
                return "{\"url\":\"" + url + "\", \"url1\":\"" + url1 + "\", \"state\":\"ok\"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.getLocalizedMessage();
                }
            }
        }
        return "";
    }

    @ResponseBody
    @PostMapping("savePhoto")
    @ApiOperation("保存拍照")
    public String savePhoto(@RequestBody JSONObject data) throws Exception {

        logger.info("savePhoto方法执行开始：传入参数为   " + data);
        long start = System.currentTimeMillis();

        Map<String, Object> datas = new HashMap<String, Object>();
        String baseImg = data.getString("baseImg");
        String cm000034name = DateUtils.format(new Date(), "yyyyMMddHHmmss");
        //定义一个正则表达式的筛选规则，为了获取图片的类型
        String rgex = "data:image/(.*?);base64";
        String type = getSubUtilSimple(baseImg, rgex);
        //去除base64图片的前缀
        baseImg = baseImg.replaceFirst("data:(.+?);base64,", "");
        byte[] b;
        byte[] bs;
        OutputStream os = null;
        String fileName = "";
        String nowDate = "";
        // 格式化并获取当前日期（用来命名）
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        nowDate = format.format(new Date());
        //把图片转换成二进制
        b = Base64.decode(baseImg.replaceAll(" ", "+"));
        //随机生成图片的名字，同时根据类型结尾
        fileName = UUID.randomUUID().toString() + "." + type;
        BASE64Decoder d = new BASE64Decoder();
        // 保存
        try {
            bs = d.decodeBuffer(Base64.encode(b));
            if (Constants.storeLocal) {
//				os = new FileOutputStream(imageFile);
                os.write(bs);
            } else {
                //上传Byte数组
                CloudStorageConfig config = new CloudStorageConfig();
                config.setAliyunAccessKeyId(Constants.accessKeyId);
                config.setAliyunAccessKeySecret(Constants.accessKeySecret);
                config.setAliyunEndPoint(Constants.endpoint);
                config.setAliyunBucketName(Constants.bucketName);
                config.setAliyunDomain("https://pulilai.oss-cn-beijing.aliyuncs.com");
                config.setAliyunPrefix("paizhao");
                String url = new AliyunCloudStorageService(config).uploadSuffix(bs, "_" + cm000034name + "." + type);
                long end = System.currentTimeMillis();
                logger.info("savePhoto方法执行结束：返回值为   " + "{\"url\":\"" + url + "\", \"state\":\"ok\"}");
                logger.info(end - start + "------------计算时间------------");
                return "{\"url\":\"" + url + "\", \"state\":\"ok\"}";
            }
        } catch (Exception e) {
            logger.error("保存信息失败,错误原因:" + e.getMessage(), e);
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.getLocalizedMessage();
                }
            }
        }
        return "img" + Constants.separator + nowDate + Constants.separator + fileName;
    }

    @GetMapping("getFiles")
    @ApiOperation("获取文件")
    public ArrayList<String> getFiles(@RequestParam String pathName) {
        logger.info("getFiles方法执行开始：传入参数为pathName   " + pathName);
        String path = File.separator + "www" + File.separator + "server" + File.separator
                + "apache-tomcat-8.5.32" + File.separator + "webapps" + File.separator + "wxTools" + File.separator + "files";
        String pathNameT = "";
        if ("doc".equals(pathName))
            pathNameT = path;
        else
            pathNameT = pathName;
        logger.info("getFiles方法执行开始：传入参数为pathNameT   " + pathNameT);
        ArrayList<String> listFileName = new ArrayList<String>();
        GetFiles.getAllFileName(pathNameT, listFileName);
        Collections.sort(listFileName, new Comparator<Object>() {
            @Override
            public int compare(Object obj1, Object obj2) {
                return ((String) obj1).toUpperCase().compareTo(((String) obj2).toUpperCase());
            }
        });
        Collections.reverse(listFileName);
        for (String name : listFileName) {
            System.out.println(name);
        }
        logger.info("getFiles方法执行结束：返回值为   " + listFileName);
        return listFileName;
    }

    @GetMapping("getImages")
    @ApiOperation("获取图片")
    public ArrayList<String> getImages(@RequestParam String pathName, @RequestParam int pathSize) {
        logger.info("getImages方法执行开始：传入参数为pathName   " + pathName + "---" + pathSize);
        String filePath = pathName == null ? "paizhao" : pathName;
        int num = pathSize == 0 ? 10 : pathSize;
        List<OSSObjectSummary> sums = new Test().getFileList(num, filePath);
        ArrayList<String> listFileName = new ArrayList<>();
        for (OSSObjectSummary s : sums) {
            listFileName.add("https://pulilai.oss-cn-beijing.aliyuncs.com/" + s.getKey());
        }
        Collections.sort(listFileName, new Comparator<Object>() {
            @Override
            public int compare(Object obj1, Object obj2) {
                return ((String) obj1).toUpperCase().compareTo(((String) obj2).toUpperCase());
            }
        });
        Collections.reverse(listFileName);
        logger.info("getImages方法执行结束：返回值为   " + listFileName);
        return listFileName;
    }

    public static String getSubUtilSimple(String soap, String rgex) {
        Pattern pattern = Pattern.compile(rgex);
        Matcher m = pattern.matcher(soap);
        while (m.find()) {
            return m.group(1);
        }
        return "";
    }

}
